﻿using UnityEngine;
using System.Collections;

public class Dragonfly_Controller : MonoBehaviour {
	private int moveX;
	private int moveY;
	public float speed = 10f;
	private Transform enemyShip;
	private GameObject pRef; 
	public AudioClip explosionSound;
	public int impactDamage = 30;
	public int dragonflyHealth = 1;

	// holds the distance between the ship and the player
	private float distance;

	// holds the rotation adjustment for the ship to face the player
	private Vector3 targetRot;

	// the vector that the ship partially rotates around to attack the player
	private Vector3 attackVector;

	// total degrees in which the ship has rotated around the attack vector
	private int tDeg;

	// holds the direction the ship was headed in toward the player
	// before entering attacking state
	private Vector3 direction;

	// the rate of fire the ship has
	public float fireRate;

	// the time until the ship is able to fire again
	private float nextFire;

	// the location the shot comes from
	public Transform weaponShotPosition;

	// the shot type
	public GameObject weaponShot;

	private bool dead = false;

	// ship AI states
	public enum States
	{
		asleep = 0,
		following = 1,
		attacking = 2,
		retreating = 3
	}

	// define States as a var and set default to asleep
	public States currentState = States.asleep;

	// Update is called once per frame
	void Start()
	{
		//set the transform data to enemyShip var
		enemyShip = transform;

		// set the current state to following the player
		currentState = States.following;
	}

	void Update () {

		if (!dead)
		{
		// get our player references
		pRef = GameObject.FindGameObjectWithTag("Player");

		switch (currentState)
		{
			// do nothing if the ship is asleep
			case States.asleep:
				break;
			case States.following:
				// calculate the distance between the ship and the player
				distance = Vector3.Distance(this.transform.position, pRef.transform.position); 

				// if the ship is not close enough, move toward the player
				if (distance > 5f)
					transform.position = Vector3.MoveTowards (this.transform.position, pRef.transform.position, speed * Time.deltaTime);
				else // otherwise, set the attack vector and begin attacking
				{	
					attackVector = pRef.transform.position;
					currentState = States.attacking;
				}

				direction = this.transform.forward * 100;
				direction.z = 0;
				//Debug.Log ("Setting direction " + direction);
				break;
			case States.attacking:
				// if the total degrees turned is less than a half circle
				if (tDeg < 180)
				{
					// increment the total degrees
					tDeg += 1;

					// rotate the ship around player's saved location
					transform.RotateAround(attackVector, Vector3.back, (speed * 8) * Time.deltaTime);

					// only allow the ship to fire if the alloted time
					// has passed
					if (Time.time > nextFire)
					{
						nextFire = Time.time + fireRate;	
						Instantiate(weaponShot, weaponShotPosition.position, enemyShip.rotation);			
					}
				}
				else // otherwise, set the total degrees to 0 and retreat
				{
					tDeg = 0;
					currentState = States.retreating;
				}
				break;
			case States.retreating:
				// if the enemy ship has reached the edge of the screen
				if (enemyShip.position.x >= 30 || enemyShip.position.x <= -30 || enemyShip.position.y >= 20 || enemyShip.position.y <= -20)
				{	
					// reposition the ship depending on a random value 
					// choosing left, top, right, or bottom of screen
					switch (Random.Range(1, 4))
					{
						case 1: // left side
							enemyShip.position = new Vector3(-30, Random.Range(-20, 20), enemyShip.position.z);
							break;
						case 2: // top
							enemyShip.position = new Vector3(Random.Range(-30, 30), 20, enemyShip.position.z); 
							break;
						case 3: // right side
							enemyShip.position = new Vector3(30, Random.Range(-20, 20), enemyShip.position.z);
							break;
						case 4: // bottom
							enemyShip.position = new Vector3(Random.Range(-30, 30), -20, enemyShip.position.z);
							break;
					}

					// set the current state back to following now
					// that the ship is repositioned
					currentState = States.following;
				}
				else 
				{	
					// retreat the ship
					transform.position = Vector3.MoveTowards(this.transform.position, direction, speed * Time.deltaTime);
					transform.LookAt(direction, Vector3.back);
				}
				break;
		}

		// only face the player if not retreating
		if (currentState != States.retreating)
		{
			// get the rotation vector between the ship and the player
			targetRot = new Vector3(pRef.transform.position.x, pRef.transform.position.y, this.transform.position.z);

			// adjust the x and y values of the rotation to make the rotation smooth
			targetRot.x = Mathf.Lerp(transform.position.x, targetRot.x, speed * Time.deltaTime);
			targetRot.y = Mathf.Lerp(transform.position.y, targetRot.y, speed * Time.deltaTime);

			// make the ship look at the adjusted vector
			this.transform.LookAt(targetRot, Vector3.back); 
		}
		                
		//Wrap enemy ship around screen on exit
			if(enemyShip.position.x >= 38)
			{
				enemyShip.position = new Vector3(-38, enemyShip.position.y, enemyShip.position.z);
			}
			else if(enemyShip.position.x <= -38)
			{
				enemyShip.position = new Vector3(38, enemyShip.position.y, enemyShip.position.z);
			}
			else if(enemyShip.position.y >= 20)
			{
				enemyShip.position = new Vector3(enemyShip.position.x,-20, enemyShip.position.z);
			}
			else if(enemyShip.position.y <= -20)
			{
				enemyShip.position = new Vector3(enemyShip.position.x,20, enemyShip.position.z);
			}
		}
	}

	void OnTriggerEnter(Collider other){
		// if the trigger hit is the player
		if (other.tag == "Player") {
			GameManager.playerHealth-=impactDamage;//Cause damage to the player on impact
			audio.PlayOneShot(explosionSound);
			// decrease health by 1
			dragonflyHealth--;

			// if health is less than 0
			if (dragonflyHealth <= 0)
			{

				dead = true;
				// disable the renderer, collider, and destroy the ship
				renderer.enabled = false;
				collider.enabled = false;
				Destroy(this.gameObject,0);
			}
		}
		if (other.tag == "Bullet") {
			audio.PlayOneShot(explosionSound);			
			dragonflyHealth--;
			Destroy(other.gameObject,0);
			
			if (dragonflyHealth <= 0)
			{
				;
				dead = true;
				renderer.enabled = false;
				collider.enabled = false;
				Destroy(this.gameObject,0);
			}
		}
	}
}
